﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using ESRI.ArcGIS.Carto;
using PlanningGIS.Framework;
using PlanningGIS.Util.Net;
using PlanningGIS.Win.Controls;
using PlanningGIS.ArcGIS;
using System.IO;

namespace PlanningGIS.Raster
{
    public partial class FrmShop : Office2007Form
    {
        private const string ID = "ID";
        private const string NAME = "名称";
        private const string FOLDER = "文件目录";
        private const string FORMATE = "文件格式";

        private IMap pMap;
        private DataTable dataTable;

        private bool hasClear = false;

        /// <summary>
        /// 实例对象
        /// </summary>
        private static FrmShop shopShop;
        /// <summary>
        /// 创建实例
        /// </summary>
        /// <returns></returns>
        public static FrmShop GetShopFrm()
        {
            if (shopShop == null || shopShop.IsDisposed)
            {
                shopShop = new FrmShop();
            }
            return shopShop;
        }

        public bool HasClear
        {
            get { return hasClear; }
        }

        public IMap Map
        {
            set { pMap = value; }
        }

        /// <summary>
        /// 添加查询结果到购物车
        /// </summary>
        /// <param name="dt">查询结果</param>
        /// <param name="type">添加方式，0为新建、1为追加、2为在已有结果集中查询</param>
        public void Add2Shop(DataTable dt, int type)
        {
            try
            {
                dataGridViewX1.DataSource = null;
                hasClear = false;
                IEnumerable<DataRow> query;
                switch (type)
                {
                    case 0:
                        dataTable = dt;
                        break;

                    case 1:
                        query = dataTable.AsEnumerable().Union(dt.AsEnumerable(), DataRowComparer.Default);
                        dataTable = query.CopyToDataTable();
                        break;

                    case 2:
                        query = dataTable.AsEnumerable().Intersect(dt.AsEnumerable(), DataRowComparer.Default);
                        dataTable = query.CopyToDataTable();
                        break;

                    default:
                        break;
                }

                dataGridViewX1.DataSource = dataTable;

                foreach (DataGridViewColumn dgvc in dataGridViewX1.Columns)
                {
                    if (dgvc.Name == ID) dgvc.Visible = false;
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("添加到购物车失败:" + ex.Message);
            }
        }

        public FrmShop()
        {
            InitializeComponent();
        }

        private void FrmShop_Load(object sender, EventArgs e)
        {
            dataGridViewX1.MultiSelect = true;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (dataGridViewX1.SelectedRows.Count == 0) return;
            if (pMap == null) return;

            try
            {
                string localPath = AppConfig.SystemConfig.FTP.LocalPath;
                string remotePath = @"\\" + AppConfig.SystemConfig.FTP.Server + "\\" + AppConfig.SystemConfig.FTP.ShareDir;
                string username = AppConfig.SystemConfig.FTP.UserName;
                string password = AppConfig.SystemConfig.FTP.Password;

                int rst = NetFileService.Connect(remotePath, localPath, username, password,false);
                if (rst != 0)
                {
                    MsgHelper.ShowWarningMsgbox("共享文件夹连接失败,请检查网络!");
                    return;
                }

                foreach (DataGridViewRow dgvr in dataGridViewX1.SelectedRows)
                {
                    string id = dgvr.Cells[ID].Value.ToString();
                    string name = dgvr.Cells[NAME].Value.ToString();
                    string folder = dgvr.Cells[FOLDER].Value.ToString();
                    string formate = dgvr.Cells[FORMATE].Value.ToString();

                    string fullName = localPath + "\\" + folder + "\\" + id + formate;

                    if (File.Exists(fullName) == false)
                    {
                        MsgHelper.ShowWarningMsgbox("网络映射盘中找到不到相应的栅格数据，请先手动断开网络驱动器【" + localPath + "】，再试一次。");
                        break;
                    }

                    ILayer pLayer = LayerHelper.GetRasterLayer(fullName);
                    pLayer.Name = name;

                    pMap.AddLayer(pLayer);
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("加载栅格数据失败:" + ex.Message);
            }

        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            dataGridViewX1.DataSource = null;
            dataGridViewX1.Rows.Clear();
            dataTable = null;
            hasClear = true;
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (dataGridViewX1.SelectedRows.Count == 0) return;

            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowNewFolderButton = true;
            fbd.Description = "选择导出目录";
            if (fbd.ShowDialog() != DialogResult.OK) return;

            prgExport.Maximum = dataGridViewX1.SelectedRows.Count;
            prgExport.Value = 0;

            this.Cursor = Cursors.WaitCursor;

            try
            {
                string path = path = RasterHelper.FtpPath;
                if (string.IsNullOrWhiteSpace(path))
                {
                    MsgHelper.ShowErrorMsgbox("共享文件访问失败，可能是网络连接失败");
                    return;
                }
                if (!path.EndsWith("\\")) path += "\\";
                foreach (DataGridViewRow dgvr in dataGridViewX1.SelectedRows)
                {
                    prgExport.Value++;

                    string id = dgvr.Cells[ID].Value.ToString();
                    string name = dgvr.Cells[NAME].Value.ToString();
                    string folder = dgvr.Cells[FOLDER].Value.ToString();
                    //string formate = dgvr.Cells[FORMATE].Value.ToString();
                    //string[] fileList = RasterHelper.Ftp.GetFileList(folder, id + ".*");
                    string fpath = path + folder;
                    string[] fileList = Directory.GetFiles(fpath, id + ".*");
                    if (fileList == null || fileList.Length == 0) continue;
                    for (int i = 0; i < fileList.Length; i++)
                    {
                        string file = fileList[i];
                        if (string.IsNullOrEmpty(file) || string.IsNullOrWhiteSpace(file)) continue;
                        string[] strs = file.Split('.');
                        string ext = strs[strs.Length - 1];
                        File.Copy(file, fbd.SelectedPath + "\\" + name + "." + ext);
                        //RasterHelper.Ftp.Download(folder + "\\" + file, fbd.SelectedPath + "\\" + name + "." + ext);
                    }
                }

                MsgHelper.ShowInfomationMsgbox("导出完毕。");
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("导出失败：" + ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
                prgExport.Maximum = 0;
                prgExport.Value = 0;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Visible = false;
        }

        private void FrmShop_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Visible = false;
        }
    }
}
